﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApp.Data;
using System.Web.Security;

namespace WebApp.Controllers
{
    public class LoginController : Controller
    {
        //
        // GET: /Login/

        public ActionResult Index()
        {
            if (Convert.ToBoolean(Session["remember"]))
            {  
                HttpCookie existingCookie = Request.Cookies["userName"];
                if (existingCookie != null)
                {
                    // force to expire it
                    return RedirectToAction("Index", existingCookie != null ? "Home" : "Login");
                }
            }
            return View();
        }

        public ActionResult Authentication(string user, string password, bool? rememberMe)
        {
            using (var db = new PAVINGDataContext())
            {
                bool remember = Convert.ToBoolean(rememberMe);
                var tmp = db.tbl_users.SingleOrDefault(u => u.user_login_name.Equals(user) && u.user_password.Equals(password));

                if (tmp != null)
                {
                    Session["remember"] = remember;
                    Session["userid"] = tmp.user_id;
                    Session["userloginname"] = tmp.user_login_name;
                    Session["usertype_id"] = tmp.user_type_id;
                }
                FormsAuthentication.SetAuthCookie(user, remember);
                if (remember)
                {
                    // check if cookie exists and if yes update
                    HttpCookie existingCookie = Request.Cookies["userName"];
                    if (existingCookie != null)
                    {
                        // force to expire it
                        existingCookie.Value = user;
                        existingCookie.Expires = DateTime.Now.AddHours(-20);
                    }

                    // create a cookie
                    HttpCookie newCookie = new HttpCookie("userName", user);
                    newCookie.Expires = DateTime.Today.AddMonths(12);
                    Response.Cookies.Add(newCookie);
                }
                return RedirectToAction("Index", tmp != null ? "Home" : "Login");
            }
            
        }

        public ActionResult Logout()
        {
            if (Request.Cookies["userName"] != null)
            {
                var c = new HttpCookie("userName");
                c.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(c);
            }
            Session["remember"] = null;
            Session["userid"] = null;
            Session["userloginname"] = null;
            Session["usertype_id"] = null;

            return RedirectToAction("Index", "Login");
        }
    }
}
